package com.botarena.server.servlets.rpc;

import java.util.logging.Logger;

import com.botarena.client.BotArena;
import com.botarena.client.account.remote.AccountAccess;
import com.botarena.server.model.Account;
import com.botarena.server.services.AccountService;
import com.botarena.server.services.BotService;
import com.botarena.shared.UserHomeInfo;
import com.botarena.shared.UserInfo;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class AccountAccessServlet extends RemoteServiceServlet implements AccountAccess {

	private static final long serialVersionUID = 5880762556674155038L;
	
	private static final Logger log = Logger.getLogger(BotArena.class.getName());
	
	private static final AccountService accountService = new AccountService();
	private static final BotService botService = new BotService();

	@Override
	public UserInfo getUserInfo(String requestUri) {
		UserInfo loginInfo = new UserInfo();
		
		loginInfo.setLoggedIn(accountService.isLoggedIn());
		if (loginInfo.isLoggedIn()) {
			User user = accountService.getGoogleUser();
			loginInfo.setEmailAddress(user.getEmail());
			loginInfo.setNickname(user.getNickname());
			loginInfo.setLogoutUrl(accountService.getLogoutURL(requestUri));
			
			Account account = accountService.getAccount(user);
			if (account != null) {
				loginInfo.setHasAccount(true);
				loginInfo.setKey(KeyFactory.keyToString(account.getKey()));
				loginInfo.setName(account.getName());
				loginInfo.setAdmin(accountService.isAdmin());
				String avatarUrl = accountService.getAvatarURL(account);
				loginInfo.setAvatarUrl(avatarUrl);
			}
		} else {
			loginInfo.setLoginUrl(accountService.getLoginURL(requestUri));
		}
		
		log.info("UserInfo: " + loginInfo.toString());
		
		return loginInfo;
	}

	@Override
	public UserHomeInfo getHomeInfo(String userKey) {
		UserHomeInfo ret = new UserHomeInfo();
		Account account = accountService.getByKey(userKey);
		ret.setAvatar(accountService.getAvatarURL(account));
		ret.setBots(botService.getUserBotsInfo(account.getKey()));
		ret.setName(account.getName());
		return ret;
	}

}
